# -*- coding: cp1256 -*-
#########################################################################
## This scaffolding model makes your app work on Google App Engine too
#########################################################################
if 0:
    from gluon.sql import *
    from gluon.validators import *


if request.env.web2py_runtime_gae:            # if running on Google App Engine
    db = DAL('gae')                           # connect to Google BigTable
                                              # optional DAL('gae://namespace')
    session.connect(request, response, db = db) # and store sessions and tickets there
    ### or use the following lines to store sessions in Memcache
    # from gluon.contrib.memdb import MEMDB
    # from google.appengine.api.memcache import Client
    # session.connect(request, response, db = MEMDB(Client()))
else:                                         # else use a normal relational database
    db = DAL('sqlite://storage.sqlite')       # if not, use SQLite or other DB
## if no need for session
# session.forget()

#########################################################################
## Here is sample code if you need for
## - email capabilities
## - authentication (registration, login, logout, ... )
## - authorization (role based authorization)
## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss)
## - crud actions
## (more options discussed in gluon/tools.py)
#########################################################################

from gluon.tools import *
mail = Mail()                                  # mailer
auth = Auth(globals(),db)  # authentication/authorization
crud = Crud(globals(),db)                      # for CRUD helpers using auth
service = Service(globals())                   # for json, xml, jsonrpc, xmlrpc, amfrpc
plugins = PluginManager()

mail.settings.server = 'logging' or 'smtp.gmail.com:587'  # your SMTP server
mail.settings.sender = 'you@gmail.com'         # your email
mail.settings.login = 'username:password'      # your credentials or None

auth.settings.hmac_key = 'sha512:99444de8-ef5f-4230-b437-04a554e1c96d'   # before define_tables()
#auth.define_tables()                           # creates all needed tables
auth.settings.mailer = mail                    # for user email verification
auth.settings.registration_requires_verification = False
auth.settings.registration_requires_approval = False
auth.messages.verify_email = 'Click on the link http://'+request.env.http_host+URL('default','user',args=['verify_email'])+'/%(key)s to verify your email'
auth.settings.reset_password_requires_verification = True
auth.messages.reset_password = 'Click on the link http://'+request.env.http_host+URL('default','user',args=['reset_password'])+'/%(key)s to reset your password'

#########################################################################
## If you need to use OpenID, Facebook, MySpace, Twitter, Linkedin, etc.
## register with janrain.com, uncomment and customize following
# from gluon.contrib.login_methods.rpx_account import RPXAccount
# auth.settings.actions_disabled=['register','change_password','request_reset_password']
# auth.settings.login_form = RPXAccount(request, api_key='...',domain='...',
#    url = "http://localhost:8000/%s/default/user/login" % request.application)
## other login methods are in gluon/contrib/login_methods
#########################################################################

crud.settings.auth = None                      # =auth to enforce authorization on crud

#########################################################################
## Define your tables below (or better in another model file) for example
##
## >>> db.define_table('mytable',Field('myfield','string'))
##
## Fields can be 'string','text','password','integer','double','boolean'
##       'date','time','datetime','blob','upload', 'reference TABLENAME'
## There is an implicit 'id integer autoincrement' field
## Consult manual for more options, validators, etc.
##
## More API examples for controllers:
##
## >>> db.mytable.insert(myfield='value')
## >>> rows=db(db.mytable.myfield=='value').select(db.mytable.ALL)
## >>> for row in rows: print row.id, row.myfield
#########################################################################

# after
# auth = Auth(globals(),db)

# to do: add activity and badge attributes 
auth.settings.table_user_name  = 'users'
auth.settings.login_next = URL('default', 'user/profile') # This will make user redirected to index page after login
auth.settings.login_url = URL('default', 'index') # This will make user redirected to index page after login
auth.settings.logged_url = URL('places', 'search')

db.define_table(
    auth.settings.table_user_name,
    Field('first_name', length=128, default=''),
    Field('last_name', length=128, default=''),
    Field('email', length=128, default='', unique=True),
    Field('password', 'password', length=512, readable=False, label='Password'),
    Field('registration_key', length=512, writable=False, readable=False, default=''),
    Field('reset_password_key', length=512, writable=False, readable=False, default=''),
    Field('registration_id', length=512, writable=False, readable=False, default=''),
    Field('birthdate', 'date'),
    Field('gender', requires=IS_IN_SET(['male', 'female'])),
    Field('picture', 'blob'),
    Field('bio', 'string'),
    Field('current_city', 'string'),
    Field('hometown', 'string'),
    Field('address', 'string'),
    Field('phone', 'string'),
    Field('facebook_id', 'string'),
    Field('twitter_id', 'string'),
    Field('fav_places', 'list:reference db.places'),
    Field('liked_places', 'list:reference db.places'),
    Field('following', 'list:reference db.users'),
    Field('followers', 'list:reference db.users'),
    Field('checkins', 'list:reference db.checkins')
)

custom_auth_table = db[auth.settings.table_user_name] # get the custom_auth_table
custom_auth_table.first_name.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty)
custom_auth_table.last_name.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty)
custom_auth_table.password.requires = [CRYPT()]
custom_auth_table.email.requires = [IS_EMAIL(error_message=auth.messages.invalid_email), IS_NOT_IN_DB(db, custom_auth_table.email)]
auth.settings.table_user = custom_auth_table # tell auth to use custom_auth_table

custom_auth_table.fav_places.requires = IS_IN_DB(db, 'places.id', multiple=True)
custom_auth_table.liked_places.requires = IS_IN_DB(db, 'places.id', multiple=True)
custom_auth_table.facebook_id.requires = IS_NOT_IN_DB(db, 'users.facebook_id')
custom_auth_table.twitter_id.requires = IS_NOT_IN_DB(db, 'users.twitter_id')
custom_auth_table.followers.requires = IS_IN_DB(db, 'users.id', multiple=True)
custom_auth_table.followers.requires = IS_IN_DB(db, 'users.id', multiple=True)


# before
# auth.define_tables()
auth.define_tables(username=False)                           # creates all needed tables
#####################################################
# categories
db.define_table('categories',
                Field('name', 'string')
)

db.categories.name.requires = IS_NOT_IN_DB(db, 'categories.name')
#####################################################
# tags 
db.define_table('tags',
                Field('name', 'string')
)

db.tags.name.requires = IS_NOT_IN_DB(db, 'tags.name')
#####################################################
# places 
db.define_table('places', 
                Field('name'),
                Field('long', 'double'),
                Field('lat', 'double'),
                Field('likes', 'integer'),
                Field('dislikes', 'integer'),
                Field('category', 'integer'),
                Field('tags', 'list:reference db.tags'),
                Field('comments', 'list:reference db.comments'),
                Field('checkins', 'list:reference db.checkins')
                )
db.places.tags.requires = IS_IN_DB(db, 'tags.id', multiple=True)
db.places.comments.requires = IS_IN_DB(db, 'users.id', multiple=True)
#####################################################
# comments
db.define_table('comments',
                Field('user', 'integer'),
                Field('content', 'string'),
                Field('datetime', 'datetime')
                )
db.comments.datetime.requires = IS_DATETIME()
#####################################################
# checkins
db.define_table('checkins',
                Field('user', 'integer'),
                Field('place', 'integer'),
                Field ('datetime' , 'datetime'))
db.checkins.datetime.requires = IS_DATETIME()
#####################################################
